<template>
  <div class="createForm">
    <div class="head">
      <div class="back" @click="back">返回</div>
      <div class="btn">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="success" @click="preview">预览</el-button>
      </div>
    </div>
    <div class="content">
      <div class="left">
        <div class="field">
          <p class="title">通用字段</p>
          <ul>
            <li
              v-for="(item,index) in fields.normal"
              :class="index"
              :key="item.TYP"
              @click="selectField(item)"
            >
              <svg-icon :icon-class="item.icon"></svg-icon>
              <p>{{item.label}}</p>
            </li>
          </ul>
        </div>
        <div class="field">
          <p class="title">联系信息字段</p>
          <ul>
            <li
              v-for="(item,index) in fields.contact"
              :class="index"
              :key="item.TYP"
              @click="selectField(item)"
            >
              <svg-icon :icon-class="item.icon"></svg-icon>
              <p>{{item.label}}</p>
            </li>
          </ul>
        </div>
      </div>
      <div class="main onscroll">
        <div class="formHead" @click="selecedHead">
          <h2>{{formHead.formHead}}</h2>
          <p class="desc">{{formHead.formDesc}}</p>
        </div>
        <ul>
          <li class="item" v-for="(item,index) in editList" :key="index" @click="selectEdit(item)">
            <formItem :item="item" />
            <div class="btn">
              <span style="background: red" @click="plus(item)">+</span>
              <span style="background: lime" @click="reduce(index)">-</span>
              <span style="background: yellow" @click="moveUp(item,index)" v-show="index !== 0">↑</span>
              <span
                style="background: lightblue"
                @click="moveDown(item,index)"
                v-show="index < editList.length-1"
              >↓</span>
            </div>
          </li>
          <li class="pcsubmint" @click="selectedSubmit">
            <el-button type="info">{{formHead.BTNTXT}}</el-button>
          </li>
        </ul>
      </div>
      <div class="right">
        <div class="formProps" v-if="currProperty[propertys.formHead]">
          <p class="title">表单属性</p>
          <ul class="onscroll">
            <li>
              <p>表单名称：</p>
              <el-input placeholder="请输入内容" v-model="formHead.formHead"></el-input>
            </li>
            <li>
              <p>表单描述：</p>
              <textarea name id cols="30" rows="2" v-model="formHead.formDesc"></textarea>
            </li>
          </ul>
        </div>
        <div class="btn" v-else-if="currProperty.BTNTXT">
          <p class="title">提交按钮属性</p>
          <div class="btnEdit">
            <p>按钮文本：</p>
            <el-input placeholder="请输入内容 " v-model="formHead.BTNTXT">{{formHead.BTNTXT}}</el-input>
          </div>
        </div>
        <div class="fieldProps" v-else>
          <p class="title">字段属性 - {{current.LBL}}</p>
          <ul class="onscroll">
            <li v-if="currProperty[propertys.fieldName]">
              <p>字段名称：</p>
              <textarea name id cols="30" rows="2" v-model="current.LBL">单行文本</textarea>
            </li>
            <li v-if="currProperty[propertys.fieldDesc]">
              <p>字段说明：</p>
              <textarea name id cols="30" rows="2" v-model="current.DESC"></textarea>
            </li>
            <li v-if="currProperty[propertys.fieldOptions]">
              <p>
                选择项：
                <span class="editIcon">
                  <svg-icon icon-class="edit" class-name="edit-style"></svg-icon>
                  <el-button
                    v-if="current.TYP === 'radio'"
                    type="text"
                    @click="$refs.radioOptions.open()"
                  >批量编辑</el-button>
                  <el-button
                    v-else
                    type="text"
                    @click="$refs.checkboxOptions.open(current.OPTIONS)"
                  >批量编辑</el-button>
                </span>
              </p>
              <el-checkbox-group
                v-if="current.TYP === 'checkbox'"
                :min="current.MIN"
                :max="current.MAX"
                v-model="checkboxSelected"
              >
                <el-checkbox
                  v-for="(item,index) in current.OPTIONS"
                  :key="index"
                  :label="index"
                >{{item.VAL}}</el-checkbox>
              </el-checkbox-group>
              <el-radio-group v-else v-model="radioSelected">
                <el-radio
                  v-for="(item,index) in current.OPTIONS "
                  :key="index"
                  :label="index"
                >{{item.VAL}}</el-radio>
              </el-radio-group>
            </li>
            <li v-if="currProperty[propertys.fieldRange]">
              <p>范围：</p>
              <p class="range">
                <el-input placeholder="最小长度" clearable v-model="current.MIN"></el-input>
                <span>-</span>
                <el-input placeholder="最大长度" clearable v-model="current.MAX"></el-input>
              </p>
            </li>
            <li v-if="currProperty[propertys.DateFormat]">
              <p>日期格式：{{current.DateFormat}}</p>
              <!-- <el-select v-model="current.DateFormat" placeholder="请选择">
                <el-option v-for="item in current.DateFormats" :key="item.value" :value="item.value">{{item.value}}</el-option>
              </el-select>-->
            </li>
            <!-- <li v-if="currProperty[propertys.DateRange]">
              <p>范围：</p>
              <div class="range">
                <el-date-picker
                  v-model="date"
                  type="daterange"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions2"
                ></el-date-picker>
              </div>
            </li>-->
            <li v-if="currProperty[propertys.fieldDate]">
              <p>默认值：</p>
              <el-date-picker
                v-model="current.DATE"
                align="right"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions1"
              ></el-date-picker>
            </li>
            <li v-if="currProperty[propertys.fieldDefault]">
              <p>默认值：</p>
              <el-input
                placeholder="请输入内容 "
                v-model="current.DEFAULT"
                :minlength="current.MIN"
                :maxlength="current.MAX"
                show-word-limit
              ></el-input>
            </li>
            <li class="number" v-if="currProperty[propertys.fieldNumber]">
              <p>默认值：</p>
              <el-input-number
                v-model="current.NUMBER"
                controls-position="right"
                :min="current.MIN"
                :max="current.MAX"
              ></el-input-number>
            </li>
            <li v-if="currProperty[propertys.fieldTime]">
              <p>默认值：</p>
              <el-time-select
                v-model="current.TIME"
                :picker-options="{
                  start: '08:30',
                  step: '00:15',
                  end: '18:30'
                }"
                placeholder="选择时间"
              ></el-time-select>
            </li>
            <li class="set" v-if="currProperty[propertys.fieldSet]">
              <p>上传设置：</p>
              <el-input class="size" placeholder="文件大小限制(MB) " v-model="current.SET.SIZE"></el-input>
              <el-input class="num" placeholder="文件数量限制 " v-model="current.SET.NUM"></el-input>

              <el-select
                class="el_select"
                style="margin-top:4px;width: 260px"
                v-model="fileSelected"
                multiple
                placeholder="选择指定文件类型"
              >
                <el-option
                  v-for="(item,index) in current.SET.FORMAT"
                  :key="index"
                  :value="item.VAL"
                ></el-option>
              </el-select>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <radioOptions ref="radioOptions" @selected="radioSelect"></radioOptions>
    <checkboxOptions
      ref="checkboxOptions"
      @selectedList="checkboxSelect"
      :optionList="current.OPTIONS"
    ></checkboxOptions>
  </div>
</template>


<script>
import fields from "@/config/form/field.js";
import editors from "@/config/form/editor.js";
import propertys from "@/config/form/property.js";

import formItem from "@/components/form/formItem.vue";

import radioOptions from "@/components/RadioOptions.vue";
import checkboxOptions from "@/components/CheckboxOptions.vue";

export default {
  name: "CreateForm",
  components: {
    formItem,
    radioOptions,
    checkboxOptions
  },
  data() {
    return {
      fields: fields,
      editList: [],
      propertys: propertys._total,
      currProperty: {},
      current: {},
      formHead: {},
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      pickerOptions2: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      date: ""
    };
  },
  computed: {
    radioSelected: {
      get() {
        if (this.current.OPTIONS) {
          let opts = this.current.OPTIONS;
          for (let i = 0; i < opts.length; i++) {
            if (opts[i].CHKED === "1") {
              return i;
            }
          }
        }
      },
      set(val) {
        let opts = this.current.OPTIONS;
        for (let i = 0; i < opts.length; i++) {
          if (val === i) {
            opts[i].CHKED = "1";
          } else {
            opts[i].CHKED = "0";
          }
        }
      }
    },
    checkboxSelected: {
      get() {
        let indexArr = [];
        if (this.current.OPTIONS) {
          let opts = this.current.OPTIONS;
          for (let i = 0; i < opts.length; i++) {
            if (opts[i].CHKED === "1") {
              indexArr.push(i);
            }
          }
        }
        return indexArr;
      },
      set(val) {
        let opts = this.current.OPTIONS;
        let obj = {}; // 空间 换 时间  2n, n*n
        for (let i = 0; i < val.length; i++) {
          obj[val[i]] = true;
        }
        for (let i = 0; i < opts.length; i++) {
          if (obj[i]) {
            opts[i].CHKED = "1";
          } else {
            opts[i].CHKED = "0";
          }
        }
      }
    },
    fileSelected: {
      get() {
        let arr = [];
        if (this.current.SET.FORMAT) {
          let opts = this.current.SET.FORMAT;
          for (let i = 0; i < opts.length; i++) {
            if (opts[i].CHKED === "1") {
              arr.push(opts[i].VAL);
            }
          }
        }
        return arr;
      },
      set(val) {
        let opts = this.current.SET.FORMAT;
        let obj = {}; // 空间 换 时间  2n, n*n
        for (let i = 0; i < val.length; i++) {
          obj[val[i]] = true;
        }
        for (let i = 0; i < opts.length; i++) {
          if (obj[val[i]]) {
            opts[i].CHKED = "1";
          } else {
            opts[i].CHKED = "0";
          }
        }
      }
    }
  },
  async mounted() {
    let id = this.$route.query.id;
    if (id) {
      let res = await this.$api.info({ id });
      this.formHead = res.M;
      this.currProperty = propertys["head"];
      this.editList = res.F;
    } else {
      this.formHead = JSON.parse(JSON.stringify(editors.head));
      this.currProperty = propertys["head"];
    }
  },
  methods: {
    back() {
      //this.$router.back(); //返回
      this.$router.push({ name: "Form" });
    },
    selectField(item) {
      //选择某个字段
      let edit = editors[item.TYP];
      if (edit) {
        let obj = JSON.parse(JSON.stringify(edit));
        this.editList.push(obj);
        this.selectEdit(obj);
      } else {
        console.warn("数据错误", item);
      }
    },
    selecedHead() {
      //选择表头
      this.currProperty = propertys["head"];
    },
    selectEdit(item) {
      //选择某个表单项
      this.current = item;
      this.currProperty = propertys[item.TYP];
      // console.log(item, this.currProperty);
    },

    plus(item) {
      this.editList.push(JSON.parse(JSON.stringify(item)));
    },
    reduce(index) {
      this.editList.splice(index, 1);
    },
    moveUp(item, index) {
      this.editList.splice(index, 1);
      this.editList.splice(index - 1, 0, item);
    },
    moveDown(item, index) {
      this.editList.splice(index, 1);
      this.editList.splice(index + 1, 0, item);
    },

    radioSelect(item) {
      this.current.LBL = item.label; //单选
      this.current.OPTIONS = item.options;
    },
    checkboxSelect(itemArr) {
      this.current.OPTIONS = itemArr;
    },

    async save() {
      if (this.editList.length > 0) {
        let res = await this.$api.save({ M: this.formHead, F: this.editList });
        this.formHead = res.M;
        this.editList = res.F;
        this.$message.success("保存成功");
      } else {
        this.$message.info("请选择至少一个字段");
      }
    },
    async preview() {
      if (this.editList.length > 0) {
        let res = await this.$api.save({ M: this.formHead, F: this.editList });
        this.formHead = res.M;
        this.editList = res.F;
        this.$router.push({ name: "FormView", query: { id: res.M._id } });
      } else {
        this.$message.info("请选择至少一个字段");
      }
    },
    selectedSubmit() {
      this.currProperty = propertys["submit"];
    }
  }
};
</script>

<style lang="scss" scoped>
.head {
  width: 100%;
  height: 50px;
  line-height: 50px;
  background: #eee;

  .back {
    width: 100px;
    text-align: center;
    float: left;
    margin-left: 100px;
  }
  .back:hover {
    color: #409eff;
  }
  .btn {
    width: 200px;
    float: right;
    margin-right: 50px;
  }
}

.content {
  position: relative;
  overflow: auto;
  height: 535px;
  padding: 20px;
  background: rgb(186, 198, 211);

  .left {
    width: 250px;
    float: left;
    margin-right: 20px;
    .field {
      .title {
        text-align: left;
        text-indent: 24px;
        line-height: 40px;
      }
      ul {
        background: #fff;
        overflow: hidden;
        li {
          float: left;
          width: 33%;
          height: 50px;
          text-align: center;
          margin-bottom: 6px;
          p {
            line-height: 30px;
          }
        }
      }
    }
  }
  .main {
    width: calc(100% - 650px);
    height: 500px;
    float: left;
    margin-right: 20px;
    background-color: #eaf2ff;
    padding: 0 20px;
    overflow: auto;
    .formHead {
      padding: 20px;
      line-height: 24px;
      margin-bottom: 10px;
      h2 {
        text-align: left;
      }
      p {
        text-align: left;
      }
    }
    .formHead:hover {
      background: lightgreen;
    }

    ul {
      .item {
        overflow: hidden;
        .btn {
          width: 200px;
          line-height: 30px;
          float: right;
          span {
            display: inline-block;
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            color: #fff;
            border-radius: 4px;
            margin-right: 4px;
          }
        }
      }
      li:hover /deep/ .formChild {
        background: lightcoral;
      }
    }
    .pcsubmint {
      padding: 20px 0;
      button {
        display: block;
        margin: 0 auto;
      }
    }
    .pcsubmint:hover {
      background: lightgreen;
    }
  }
  .right {
    width: 320px;
    height: 500px;
    float: left;
    background: pink;

    .title {
      text-align: left;
      text-indent: 24px;
      line-height: 40px;
    }
    .btn {
      .btnEdit {
        background: #fff;
        padding: 10px;
        p {
          line-height: 24px;
          text-align: left;
        }
      }
    }
    ul {
      background: #fff;
      padding: 10px;
      .set {
        .size {
          width: 150px;
          margin-right: 10px;
        }
        .num {
          width: 120px;
        }
      }
      li {
        margin-bottom: 4px;
        overflow: hidden;
        p {
          line-height: 24px;
          text-align: left;
          overflow: hidden;
          .editIcon {
            float: right;
          }
          span:hover {
            color: #409eff;
          }
        }
        .range {
          .el-input {
            width: 136px;
          }
          .el-date-editor {
            width: 280px;
          }
          span {
            margin: 0 5px;
          }
        }
        .el-select {
          float: left;
        }
        textarea {
          float: left;
          border: 1px solid #c0c4cc;
          border-radius: 4px;
        }
        textarea:hover {
          border: 1px solid #409eff;
        }
        .el-radio-group,
        .el-checkbox-group {
          line-height: 24px;
          .el-radio,
          .el-checkbox {
            width: 100%;
            text-align: left;
            text-indent: 6px;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss" >
.el-dialog__header {
  padding: 10px 20px;
  background: #eee;
  span {
    clear: both;
  }
}
.el-dialog__body {
  padding: 10px 20px;
}
.el-dialog__footer {
  padding: 10px 20px 50px !important;
}
</style>